<template>
  <div class="codeRain">
    <canvas id="bg"></canvas>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';

const width = window.innerWidth * devicePixelRatio;
const height = window.innerHeight * devicePixelRatio;
const fontSize = 16 * devicePixelRatio;
// 列宽
const columnWidth = fontSize;
// 列数
const columCount = Math.floor(width / columnWidth);
// 下一个字符的位置
const nextChar = new Array(columCount).fill(0);

const ctx = ref<CanvasRenderingContext2D>();

const draw = () => {
  // 绘制背景
  (ctx.value as CanvasRenderingContext2D).fillStyle = 'rgba(240, 240, 240, 0.1)';
  (ctx.value as CanvasRenderingContext2D).fillRect(0, 0, width, height);
  for (let i = 0; i < columCount; i++) {
    (ctx.value as CanvasRenderingContext2D).fillStyle = randomColor();
    const text = randomText();
    (ctx.value as CanvasRenderingContext2D).font = `${fontSize}px Roboto Mono`;
    const x = i * columnWidth;
    const y = (nextChar[i] + 1) * fontSize;
    (ctx.value as CanvasRenderingContext2D).fillText(text, x, y);
    if (y > height && Math.random() > 0.99) {
      nextChar[i] = 0;
    } else {
      nextChar[i]++;
    }
  }
};

// 随机颜色
const randomColor = () => {
  const fontColors = [
    '#33B5E5',
    '#0099CC',
    '#AA66CC',
    '#9933CC',
    '#669900',
    '#FFBB33',
    '#FF8800',
    '#FF4444',
    '#CC0000',
  ];
  return fontColors[Math.floor(Math.random() * fontColors.length)];
};

// 随机文字
const randomText = () => {
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return chars[Math.floor(Math.random() * chars.length)];
};

onMounted(() => {
  const cvs = document.getElementById('bg') as HTMLCanvasElement;
  cvs.width = width;
  cvs.height = height;
  // 获取绘图上下文
  ctx.value = cvs.getContext('2d') as CanvasRenderingContext2D;
  console.log(width, columCount);
  setInterval(() => {
    draw();
  }, 50);
});
</script>

<style lang="scss" scoped>
.codeRain {
  width: calc(100vw - 132px);
  height: calc(100vh - 32px);
}
</style>
